package com.strato.transaction.v1_0_0.mvc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.strato.mvc.api.v1_0_0.control.HttpInvoker;
import com.strato.mvc.api.v1_0_0.control.HttpInvokerInterceptor;
import com.strato.mvc.api.v1_0_0.control.PathVariableCollector;
import com.strato.mvc.api.v1_0_0.model.ModelAndView;
import com.strato.mvc.api.v1_0_0.util.RequestMeta;
import com.strato.transaction.v1_0_0.api.TransactionManager;
import com.strato.transaction.v1_0_0.api.TransactionStatus;
import com.strato.transaction.v1_0_0.api.TransactionStatusHolder;

public class TransactionInterceptor implements HttpInvokerInterceptor {

	private static final int ORDER = 100;
	private TransactionManager transactionManager;
	
	public TransactionManager getTransactionManager() {
		return transactionManager;
	}

	public void setTransactionManager(TransactionManager transactionManager) {
		this.transactionManager = transactionManager;
	}

	@Override
	public boolean canHandle(HttpServletRequest request, HttpServletResponse response, PathVariableCollector pvc, RequestMeta meta, HttpInvoker invoker) {
		return true;
	}

	@Override
	public boolean beforeInvocation(HttpServletRequest request, HttpServletResponse response, PathVariableCollector pvc, ModelAndView mav,HttpInvoker invoker) {
		TransactionStatus status=transactionManager.beginTransaction();
		TransactionStatusHolder.hold(status);
		return true;
	}

	@Override
	public void invocationSuccess(HttpServletRequest request, HttpServletResponse response, PathVariableCollector pvc, ModelAndView mav, HttpInvoker invoker) {
		TransactionStatus status = TransactionStatusHolder.get();
		transactionManager.commit(status);
	}

	@Override
	public void invocationFailed(HttpServletRequest request, HttpServletResponse response, PathVariableCollector pvc, Exception e, HttpInvoker invoker) {
		TransactionStatus status = TransactionStatusHolder.get();
		transactionManager.rollback(status);
	}

	@Override
	public void invokeFinally(HttpServletRequest request, HttpServletResponse response, PathVariableCollector pvc, HttpInvoker invoker) {
		TransactionStatus status = TransactionStatusHolder.get();
		transactionManager.endTransaction(status);
		TransactionStatusHolder.unhold();
	}

	@Override
	public int getOrder() {
		return ORDER;
	}

}
